<template>
    <div class="wrap" v-loading="loading">
        <div class="info">
            <el-avatar class="group-avatar" shape="square" :size="40" fit="cover" :src="groupInfo.avatar"></el-avatar>
            <div class="group-name">{{ groupInfo.groupname||"群聊天" }}（{{ groupInfo.personnum }}）</div>
        </div>
        <el-tabs v-model="activeName" class="group-tabs">
            <el-tab-pane label="群成员" name="user">
                <div class="list">
                <div class="scroller">
                <div class="member-item" v-for="(member) in groupMembers" :key="member.id">
                    <popoverAvatar 
                        class="member-avatar"
                        :avatar="member.avatar"
                        :nick="member.nick"
                        :wxid="member.wxid"
                        :alias="member.alias"
                        :remark="member.signature"
                        :size="60" 
                        :ismycontact="member.ismycontact === 1"
                        :gender="member.sex"
                        @add="addFriend(member)"
                        @share="share(member)"
                        @tochat="tochat(member)"
                        lazy/> 
                    <span class="member-name">{{ member.groupnick||member.nick }}</span>    
                </div>
            </div>
             
        </div>
            </el-tab-pane>
            <el-tab-pane label="邀请关系" name="invite">
                <div>
                    <table style=" =width:100%; line-height:30px" colspan="5px" rowspan="5px">
                        <tr style="text-align:center">
                            <th style="width:250px;text-align:center">邀请人</th>
                            <th style="width:80px;text-align:center">邀请人数</th>
                            <th style="text-align:center">被邀请人</th>
                        </tr>
                        <tr v-for="(record, idx) in inviteHistory" :key="idx">
                            <td>{{ record[0] }}</td>
                            <td  style="text-align:center">{{ record.length - 1 }}</td>
                            <td>
                                <span v-for="(value, idj) in record" :key="idj" style="margin-right:10px">
                                    <template v-if="idj>0">
                                    {{  value }}
                                    </template>
                                </span>
                            </td>
                        </tr>
                    </table>
                </div>
            </el-tab-pane>
        </el-tabs>
        
        <el-divider></el-divider>
        <div class="button-group">
            <el-button @click="tochat(groupInfo)" type="success">发送消息</el-button>
        </div>

        <!-- // 选择发送好友 多选 -->
        <dialogSelectFriend ref="dialogSelectFriend" />
    </div>    
</template>
<script>
import popoverAvatar from '@/components/popover-avatar'
import dialogSelectFriend from '@/components/dialog-select-friend'
import { mapMutations, mapActions, mapState } from 'vuex'

export default {
    name:"group-profile",
    props:['csid','groupno','wxaccount','account','backChatHandler'],
    components:{ popoverAvatar,dialogSelectFriend },
    data(){
        return {
            activeName:"user",
            groupInfo:{},
            groupMembers:[],
            inviteHistory:[],
            loading:true,
        }
    },
    async mounted(){
        this.loading = true
        await this.requestData()
        setTimeout(()=>this.loading = false,1000)
    },
    computed:{
        ...mapState(['chatListMap'])
    },
    watch:{
        async groupno(){
            this.loading = true
            this.groupInfo = {},
            this.groupMembers = [],
            await this.requestData()
            this.$nextTick(()=>this.loading = false)
        }    
    },
    methods: {
        ...mapMutations([ 'updateChatMap','addMessageMap','addMessageListMap','updateUIState']),
        ...mapActions(['wsSend','addChatByFriend']),
        async requestData(){
            const params = {
                csId:this.csid,
                groupNo:this.groupno,
                wxAccount:this.wxaccount
            }
            console.log(params)
            if(!this.csid || !this.groupno || !this.wxaccount)return
            return Promise.all([this.requestGroupInfo(params),this.requestGroupList(params), this.getInviteHistory(params)])
        },
        async getInviteHistory(params){
            this.$api.group.groupInviteHistory(params)
                .then(rs=>{
                    console.log(rs)
                    this.inviteHistory = Object.keys(rs).map(item=>[item, ...rs[item]]).sort((a,b)=>(a.length>b.length))
                    console.log(this.inviteHistory)
                })    
        },
        async requestGroupInfo(params){
            this.$api.group.groupInfo(params)
                .then(rs=>{
                    this.groupInfo = rs
                })    
        },
        async requestGroupList(params){
            this.$api.group.members(params)
                .then(rs=>{
                    this.groupMembers = rs
                })
               
        },
        async sendMessage(params){
            
            const { csid,wxaccount,friendwxid,message } = params 
            const { msgtype } = message;
            const msgId = +Date.now()
            delete message.id
            const msg = {
                wxAccount:wxaccount,
                msgId,
                msgid:msgId,
                friendId:friendwxid,
                msgType: msgtype,
                msgtype,
                opType: 1,
                content:JSON.stringify(message),
                chatfrom:1,
                sendstatus:-100,
            }
            this.addMessageMap(msg)
            this.addMessageListMap(msg)
            this.wsSend(msg) 
        },
        async share(member){
            if(!this.account.isonline){
                return this.$message({
                        showClose: true,
                        message: '设备离线,无法发送',
                        type: 'error'
                    });
            }
            const { csid,wxaccount,avatar,nick,alias,wxid, } = member
            const message = {
                "msgtype":13,
                "src":avatar,
                "title":nick,
                wxid,
                alias,
                "certflag":0
            }
            const selectFriends = await this.$refs.dialogSelectFriend.getSelectFriendsAsync({
                csid,
                wxaccount,
                multiple:true,
                filterType:1,
                type:1 
            })
            if(!selectFriends)return;
            selectFriends.forEach(friend=>{
                this.sendMessage({ csid,wxaccount,friendwxid:friend.friendwxid,message })   
            })
            console.log(member,selectFriends)
        },
        addFriend(user) {
            this.$prompt('添加群成员 '+user.nick+' 为好友？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue:'你好'
            }).then(({ value }) => {
                const applyMsg = value
                if(applyMsg === null) return;
                const param = {
                    memberWxId:user.wxid,
                    groupNo:user.groupno,
                    wxAccount:user.wxaccount,
                    applyMsg,
                    opType:3
                }
                this.wsSend(param)
            }).catch(() => {

            });
            
        },
        tochat(member){
            if( member.wxid ){
                const friend = {
                    csid:member.csid,
                    wxaccount:member.wxaccount,
                    friendnick:member.nick,
                    friendNick:member.nick,
                    friendwxid:member.alias||member.wxid,
                    avatar:member.avatar    
                }
                this.addChatByFriend(friend) // 添加到chat相关
            }else{
                const friend = {
                    csid:member.csid,
                    wxaccount:member.wxaccount,
                    friendnick:member.groupname,
                    friendNick:member.groupname,
                    friendwxid:member.groupno,
                    avatar:member.avatar
                }
                this.addChatByFriend(friend) 
            }

            const chatid = this.chatListMap[this.account.id][0]
            this.updateUIState({ chatid }) // ui 选中
            this.backChatHandler && this.backChatHandler()
            // this.$element.tabChange('changeTab', 'message')
        },
            
    },
}
</script>
<style scoped>
.wrap{
    display: flex;
    flex-direction: column;
    flex:1;
    width: 100%;
    height: 100%;
}
.info{
    display: flex;
    flex-direction: row;
    align-items: center;

}
.group-name{
    padding-left: 10px;
    font-size: 16px;
}
.group-tabs{
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
.group-tabs >>> .el-tabs__content{
    overflow: auto;
    flex:1;
}
.list{
    height: 100%;
    overflow: auto;
}
.button-group{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.member-avatar{
    display: block;
    
}
.member-item{
    float: left;
    margin: 5px;
    display:flex;
    flex-direction: column;
    width: 60px;
    text-align: center;
}
.member-name{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 5px 0;
    font-size: 12px;
    color: #666;
}
</style>